/***
 * 循环队列实现
 */
public class LoopQueue<T> implements Queue<T> {
    private T[] data;
    private int front, tail;
    private int size;

    public LoopQueue(int capacity) {
        data = (T[]) new Object[capacity + 1];
        front = 0;
        tail = 0;
        size = 0;
    }

    public LoopQueue() {
        this(10);
    }

    @Override
    public T dequeue() {
        if(isEmpty()){
            throw new IllegalArgumentException("cannot dequeue from an empty queue");
        }
        T t = data[front];
        data[front] = null;
        //front后移
        front = (front + 1) % data.length;
        size--;
        if(size == data.length / 4 && getCapacity() / 2 != 0){
            resize(getCapacity()  / 2);
        }
        return t;
    }

    @Override
    public void enqueue(T t) {
        //队列是否为满
        if((tail +1 ) % data.length == front){
            resize(getCapacity() * 2);
        }
        data[tail] = t;
        tail = (tail+1) % data.length;
        size++;
    }

    private void resize(int newcapacity) {
        T[] newdata = (T[]) new Object[newcapacity + 1];
        //将数据转进去
        for(int i=0;i<size;i++){
            newdata[i] = data[(i+front) % data.length];
        }
        data = newdata;
        front = 0;
        tail = size;
    }


    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return front == tail;
    }

    @Override
    public T getFront() {
        if(isEmpty()){
            throw new IllegalArgumentException("cannot dequeue from an empty queue");
        }
        return data[front];
    }

    public int getCapacity() {
        return data.length - 1;
    }

    @Override
    public String toString(){
        StringBuffer sb = new StringBuffer();
        sb.append(String.format("Queue : size=%d,capacity=%d\n",size,getCapacity()));
        sb.append("front [");
        for(int i=front;i!= tail;i = (i+1) % data.length){
            sb.append(data[i]);
            if((i+1) % data.length != tail){
                sb.append(",");
            }
        }
        sb.append("] tail");
        return sb.toString();
    }

    public static void main(String[] args) {
        LoopQueue<Integer> loopQueue = new LoopQueue<>();
        for(int i=0;i<10;i++){
            loopQueue.enqueue(i);
            System.out.println(loopQueue);
            if(i % 3 == 2 ){
                loopQueue.dequeue();
                System.out.println(loopQueue);
            }
        }
    }
}
